//
//  NetWorkManager.m
//  URLSessionTest
//
//  Created by mac on 2017/7/5.
//  Copyright © 2017年 yyb. All rights reserved.
//
#import "NetWorkManager.h"
#import "AssertMacros.h"

@interface  NetWorkManager ()
@property(nonatomic, copy) NSString *method;
@property(nonatomic, strong) NSDictionary <NSString *,id>* params;
@property(nonatomic, strong) CompletionHandler completionHandler;
@property(nonatomic, strong) NSURLSession *session;
@property(nonatomic, strong) NSMutableURLRequest *request;
@property(nonatomic, strong) NSURLSessionTask *task;
@end

@implementation NetWorkManager
- (instancetype)initWithCompletionHandler:(CompletionHandler)completionHandler {
    if (self = [super init]) {
        self.session = [NSURLSession sessionWithConfiguration:[NSURLSession sharedSession].configuration
                                                     delegate:(id <NSURLSessionDelegate>)self
                                                delegateQueue:[NSURLSession sharedSession].delegateQueue ];
        self.completionHandler = completionHandler;
    }
    return self;
}

#pragma mark - NSURLSessionDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    __block NSURLCredential *credential = nil;
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([self.security evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
            credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            if (credential) {
                disposition = NSURLSessionAuthChallengeUseCredential;
            } else {
                disposition = NSURLSessionAuthChallengePerformDefaultHandling;
            }
        } else {
            disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
        }
    } else {
        disposition = NSURLSessionAuthChallengePerformDefaultHandling;
    }
    if (completionHandler) {
        completionHandler(disposition, credential);
    }
}

- (void)fireTask {
//    NSLog(@"%@",self);
    self.task = [self.session dataTaskWithRequest:self.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        self.completionHandler(data,response,error);
    }];
    [self.task resume];
}

- (void)fire {
    self.request = [self.serializer buildRequest];
    [self fireTask];
}

@end
